package com.example.fw;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.GroupData;
import com.example.utils.SortedListOf;

public class GroupHelper extends HelperBase{

	public GroupHelper(AppManager manager) {
		super(manager);
	}
	
	public GroupHelper createGroup(GroupData groupData) {
		manager.navigateTo().groupsPage();
		initNewGroupCreation();
		fillGroupForms(groupData);
		submitGroupCreation();
		manager.navigateTo().groupsPage();
		rebuildCache();
		return this;
	}
	
	public GroupHelper modifyGroup(int groupIndex, GroupData groupData) {
		manager.navigateTo().groupsPage();	
		selectGroupByIndex(groupIndex);
		initGroupModification();
		fillGroupForms(groupData);
		submitGroupModification();
		manager.navigateTo().groupsPage();	
		rebuildCache();
		return this;
	}

	public GroupHelper removeGroup(int groupIndex) {
		manager.navigateTo().groupsPage();
		selectGroupByIndex(groupIndex);
		submitGroupDeletion();
		manager.navigateTo().groupsPage();
		rebuildCache();
		return this;
	}
	
	public SortedListOf<GroupData> getGroups() {
		if (cachedGroups == null) {
			rebuildCache();
		}
		return cachedGroups;
	}	
	
	// --------------------------------------------------------------------------------------------

	private SortedListOf<GroupData> cachedGroups;
	
	private void rebuildCache() {
		cachedGroups = new SortedListOf<GroupData>();		
		
		manager.navigateTo().groupsPage();
		List<WebElement> checkboxes = driver.findElements(By.name("selected[]"));
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
			String name = title.substring("Select (".length(), title.length() - ")".length());	
			cachedGroups.add(new GroupData().withName(name));
		}	
	}
	
	public GroupHelper initNewGroupCreation() {
		manager.navigateTo().groupsPage();
		click(By.name("new"));
		return this;
	}

	public GroupHelper submitGroupCreation() {
		click(By.name("submit"));
		cachedGroups = null;
		return this;
	}

	public GroupHelper fillGroupForms(GroupData groupData) {
		type(By.name("group_name"), groupData.getName());
		type(By.name("group_header"), groupData.getHeader());
		type(By.name("group_footer"), groupData.getFooter());
		return this;
	}

	public GroupHelper initGroupModification() {
		click(By.name("edit"));
		return this;
	}	

	public GroupHelper submitGroupModification() {
		click(By.name("update"));
		cachedGroups = null;
		return this;
	}	
	
	public GroupHelper selectGroupByIndex(int index) {
		click(By.xpath("(//input[@name='selected[]'])[" + (index +1) + "]"));
		return this;
	}
	
	public GroupHelper submitGroupDeletion() {
		click(By.name("delete"));
		cachedGroups = null;
		return this;	
	}
}
